package com.qf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.mapper.*;
import com.qf.pojo.*;
import com.qf.service.DtsGoodsAttributeService;
import com.qf.service.DtsGoodsProductService;
import com.qf.service.DtsGoodsService;
import com.qf.service.DtsGoodsSpecificationServic;
import com.qf.util.ResponseUtil;
import com.qf.vo.GoodsAllinone;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * @author YDW
 * projectName:shop-manage
 * time:2022/5/19 11:19
 * description:
 */
@Service
public class DtsGoodsServiceImpl implements DtsGoodsService {

    @Autowired
    DtsGoodsMapper goodsMapper;

    @Autowired
    DtsGoodsAttributeMapper goodsAttributeMapper;

    @Autowired
    DtsGoodsSpecificationMapper goodsSpecificationMapper;

    @Autowired
    DtsGoodsProductMapper goodsProductMapper;

    @Autowired
    DtsCategoryMapper categoryMapper;

    @Autowired
    DtsBrandMapper brandMapper;


    @Override
    public Integer getTotal() {
        Integer count = goodsMapper.selectCount(null);
        return count;
    }

    @Override
    public IPage<DtsGoods> queryPage(Integer page, Integer limit, String sort, String order, String goodsSn, String name, List<Integer> brandIds) {
        IPage<DtsGoods> ipage=new Page<>(page,limit);
        QueryWrapper qw=new QueryWrapper<>();
        if(!StringUtils.isEmpty(goodsSn)){
            qw.like("goods_sn",goodsSn);
        }
        if(!StringUtils.isEmpty(name)){
            qw.like("name",name);
        }
        if(!CollectionUtils.isEmpty(brandIds)){
            qw.in("brand_id",brandIds);
        }
        if(!StringUtils.isEmpty(sort)&&!StringUtils.isEmpty(order)){
            if(order.equals("desc")){
                qw.orderByDesc(sort);
            }else {
                qw.orderByAsc(sort);
            }
        }
        goodsMapper.selectPage(ipage,qw);
        return ipage;
    }

    @Override
    public GoodsAllinone queryDetailById(Integer id) {
        GoodsAllinone goodsAllinone=new GoodsAllinone();
        //查询商品信息
        DtsGoods goods = goodsMapper.selectById(id);
        //商品的属性信息
        LambdaQueryWrapper<DtsGoodsAttribute> qw1=new LambdaQueryWrapper<>();
        qw1.eq(DtsGoodsAttribute::getGoodsId,id);
        qw1.eq(DtsGoodsAttribute::getDeleted,false);
        List<DtsGoodsAttribute> attributes = goodsAttributeMapper.selectList(qw1);
        //商品的库存
        LambdaQueryWrapper<DtsGoodsProduct> qw2=new LambdaQueryWrapper<>();
        qw2.eq(DtsGoodsProduct::getGoodsId,id);
        qw2.eq(DtsGoodsProduct::getDeleted,false);
        List<DtsGoodsProduct> products = goodsProductMapper.selectList(qw2);
        //商品的规格
        LambdaQueryWrapper<DtsGoodsSpecification> qw3=new LambdaQueryWrapper<>();
        qw3.eq(DtsGoodsSpecification::getGoodsId,id);
        qw3.eq(DtsGoodsSpecification::getDeleted,false);
        List<DtsGoodsSpecification> specifications = goodsSpecificationMapper.selectList(qw3);
        //查询商品分类
        //获取商品的二级分类
        Integer categoryLv2 = goods.getCategoryId();
        //获取二级分类对应的一级分类
        DtsCategory dtsCategory = categoryMapper.selectById(categoryLv2);
        Integer categoryLv1 = dtsCategory.getPid();

        //存入对象
        goodsAllinone.setGoods(goods);
        goodsAllinone.setAttributes(attributes.toArray(new DtsGoodsAttribute[attributes.size()]));
        goodsAllinone.setProducts(products.toArray(new DtsGoodsProduct[products.size()]));
        goodsAllinone.setSpecifications(specifications.toArray(new DtsGoodsSpecification[specifications.size()]));
        goodsAllinone.setCategoryIds(new Integer[]{categoryLv1,categoryLv2});
        return goodsAllinone;
    }

    @Autowired
    DtsGoodsProductService productService;

    @Autowired
    DtsGoodsSpecificationServic specificationServic;

    @Autowired
    DtsGoodsAttributeService attributeService;



    @Override
    public void update(GoodsAllinone goodsAllinone) {

        //数据校验
        //商品校验
        DtsGoods goods = goodsAllinone.getGoods();
        if (goods==null){
            throw new RuntimeException("参数有误");
        }
        if(StringUtils.isEmpty(goods.getName())){
            throw new RuntimeException("商品名称不能为空");
        }
        if(StringUtils.isEmpty(goods.getGoodsSn())){
            throw new RuntimeException("商品编号不能为空");
        }
        Integer brandId = goods.getBrandId();

        //判断品牌商是否存在
        DtsBrand brand = brandMapper.selectById(brandId);
        if (brand==null){
            throw new RuntimeException("品牌商不存在");
        }
        Integer categoryId = goods.getCategoryId();

        DtsCategory dtsCategory = categoryMapper.selectById(categoryId);
        if(dtsCategory==null){
            throw new RuntimeException("分类不存在");
        }
        //商品属性校验
        DtsGoodsAttribute[] attributes = goodsAllinone.getAttributes();
        if (attributes==null||attributes.length==0){
            throw new RuntimeException("商品属性不能为空");
        }
        //商品库存校验
        DtsGoodsProduct[] products = goodsAllinone.getProducts();
        if (products==null||products.length==0){
            throw new RuntimeException("商品库存不能为空");
        }
        //商品规格校验
        DtsGoodsSpecification[] specifications = goodsAllinone.getSpecifications();
        if (specifications==null||specifications.length==0){
            throw new RuntimeException("商品规格不能为空");
        }

        //更新商品表
        goods.setUpdateTime(new Date());
        goodsMapper.updateById(goods);

        //更新库存表

        productService.updateProducts(goods.getId(),products);

        //更新规格表
        specificationServic.updateSpecifications(goods.getId(),specifications);

        //更新属性表
        attributeService.updateAttributes(goods.getId(),attributes);

    }

    @Override
    public Object delete(DtsGoods goods) {
        //判断商品是否被订单关联（未支付，支付失败）
        long count=goodsMapper.selectOrderCountById(goods.getId());
        if(count>0){
            return ResponseUtil.fail(-1,"该商品正在热卖，暂不能删除");
        }
        //商品逻辑删除
        goods.setDeleted(true);
        goodsMapper.updateById(goods);

        //商品属性逻辑删除
        attributeService.deteleByGoodsId(goods.getId());
        //商品规格逻辑删除
        specificationServic.deteleByGoodsId(goods.getId());
        //商品库存逻辑删除
        productService.deteleByGoodsId(goods.getId());
        return ResponseUtil.ok();
    }

    @Override
    public void create(GoodsAllinone goodsAllinone) {

        //数据校验
        //商品校验
        DtsGoods goods = goodsAllinone.getGoods();
        if (goods==null){
            throw new RuntimeException("参数有误");
        }
        if(StringUtils.isEmpty(goods.getName())){
            throw new RuntimeException("商品名称不能为空");
        }
        if(StringUtils.isEmpty(goods.getGoodsSn())){
            throw new RuntimeException("商品编号不能为空");
        }
        Integer brandId = goods.getBrandId();

        //判断品牌商是否存在
        DtsBrand brand = brandMapper.selectById(brandId);
        if (brand==null){
            throw new RuntimeException("品牌商不存在");
        }
        Integer categoryId = goods.getCategoryId();

        DtsCategory dtsCategory = categoryMapper.selectById(categoryId);
        if(dtsCategory==null){
            throw new RuntimeException("分类不存在");
        }
        //商品属性校验
        DtsGoodsAttribute[] attributes = goodsAllinone.getAttributes();
        if (attributes==null||attributes.length==0){
            throw new RuntimeException("商品属性不能为空");
        }
        //商品库存校验
        DtsGoodsProduct[] products = goodsAllinone.getProducts();
        if (products==null||products.length==0){
            throw new RuntimeException("商品库存不能为空");
        }
        //商品规格校验
        DtsGoodsSpecification[] specifications = goodsAllinone.getSpecifications();
        if (specifications==null||specifications.length==0){
            throw new RuntimeException("商品规格不能为空");
        }
        //添加商品
        goods.setDeleted(false);
        goods.setUpdateTime(new Date());
        goods.setAddTime(new Date());
        goodsMapper.insert(goods);
        //添加属性
        attributeService.addAttribute(goods.getId(),goodsAllinone.getAttributes());

        //添加规格
        productService.addProduct(goods.getId(),goodsAllinone.getProducts());
        //添加库存
        specificationServic.addSpecification(goods.getId(),goodsAllinone.getSpecifications());


    }
}
